package com.huan.iteye.analysis.support.impl;

import com.huan.iteye.analysis.model.EveryDayViewTotalModel;
import com.huan.iteye.analysis.repository.IteyeBlogTotalViewsRepository;
import com.huan.iteye.analysis.support.AbstractBlogAnalysisSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 每天访问总量和净增量统计
 *
 * @author huan.fu
 * @date 2018/9/18 - 14:07
 */
@Component
@Order(1)
public class EveryDayViewTotalAnalysis extends AbstractBlogAnalysisSupport {

	@Autowired
	private IteyeBlogTotalViewsRepository iteyeBlogTotalViewsRepository;

	@Override
	public String doAnalysis(List<String> workDays) {
		Map<String, EveryDayViewTotalModel> blogTotalViewsMap = iteyeBlogTotalViewsRepository.findByWorkDateIn(workDays)
				.stream()
				.map(views -> EveryDayViewTotalModel.builder().workDate(views.getWorkDate()).totalViewCnt(views.getViewCnt()).currentDayViewCnt(0L).build())
				.collect(Collectors.toMap(EveryDayViewTotalModel::getWorkDate, v -> v));

		// 数据整合
		workDays.forEach(workDay -> blogTotalViewsMap.putIfAbsent(workDay, EveryDayViewTotalModel.builder().workDate(workDay).currentDayViewCnt(0L).totalViewCnt(0L).build()));

		int len = workDays.size();
		for (int i = 0; i < len; i++) {
			// 当是最后一天时不进行分析
			if (i == len - 1) {
				continue;
			}
			// 前一天当前的访问量 = 后一天的访问总量 - 前一天的访问总量
			blogTotalViewsMap.get(workDays.get(i)).setCurrentDayViewCnt(
					blogTotalViewsMap.get(workDays.get(i + 1)).getTotalViewCnt() - blogTotalViewsMap.get(workDays.get(i)).getTotalViewCnt()
			);
		}

		return generatorHtml(workDays, blogTotalViewsMap);
	}

	/**
	 * 生成 html 代码
	 *
	 * @param workDays
	 * @param models
	 * @return
	 */
	public String generatorHtml(List<String> workDays, Map<String, EveryDayViewTotalModel> models) {
		StringBuilder builder = new StringBuilder(500);
		builder.append("<table>");
		builder.append("<caption><h3>").append("昨天博客访问总量和增量").append("</h3></caption>");
		builder.append("<thead>")
				.append("<tr>")
				.append("<th>").append("业务日期").append("</th>")
				.append("<th>").append("总访问量").append("</th>")
				.append("<th>").append("增量访问量").append("</th>")
				.append("</tr>")
				.append("</thead>")
				.append("<tbody>");

		workDays.forEach(workDay -> {
			EveryDayViewTotalModel model = models.get(workDay);
			builder.append("<tr>")
					.append("<td>").append(model.getWorkDate()).append("</td>")
					.append("<td>").append(model.getTotalViewCnt()).append("</td>")
					.append("<td>").append(model.getCurrentDayViewCnt()).append("</td>")
					.append("</tr>");
		});

		builder.append("</tbody>");
		builder.append("</table>");
		return builder.toString();
	}
}
